import JMuxmer from 'jmuxer/src/jmuxer.js'

const getJmuxer = (videoId, codec) => {
  const jmuxer = new JMuxmer({
    node: videoId,
    mode: 'video',
    video: codec,
    flushingTime: 40, // 缓冲区刷新时间
    fps: 80, // 视频的帧速率
    clearBuffer:true, // 自动清除播放的媒体缓冲区
    debug: false // 控制台中打印调试日志
  })
  return jmuxer
}

interface State {
  isPlay: boolean;  // 是否正在播放
  isVolumeOpen: boolean;
  isFrame: boolean;
  isFullScreen: boolean;
  volumeValue: number;
  streamType: string;
  speed: string;
  scale: string;
}


class bsVideo {
  private worker: Worker
  private video: HTMLElement
  private parentNode: HTMLElement
  private videoRender: JMuxmer
  public state: State
  private videoId: string

  constructor(id) {
    this.init(id)
  }

  init(id) {
    this.worker = new Worker('./static/bsxdecoder.js')
    this.parentNode = document.querySelector('#' + id)
    this.video = document.createElement('video')
    this.video.style.cssText = 'width: 100%; height: 100%;'
    this.video.setAttribute('autoplay', 'autoplay')
    this.videoId = 'video' + id
    this.video.setAttribute('id', this.videoId)
    this.parentNode.appendChild(this.video)
    this.videoRender = null
    this.worker.onmessage = (event) => {
      this.transactional(event)
    }
  }

  transactional(event) {
    if (event.data.mtype === 'initEnd') {
      setTimeout(() => {
        this.open('ws://127.0.0.1:9998/live')
      }, 500)
    } else if (event.data.mtype === 'video') {
      this.encountered(event.data.data)
    }
  }

  postMessage(data: Object) {
    this.worker.postMessage(data)
  }

  terminate () {
    this.worker.terminate()
  }

  open(socketUrl) {
    if (this.videoRender) {
      this.videoRender.destroy()
      this.videoRender = null
    }
    this.postMessage({mtype: 'open', wsUrl: socketUrl, index: 0})
  }

  encountered(data) {
    let msgBuf = data
    if (msgBuf[7] === 1 && this.videoRender) {
      this.videoRender.destroy()
      this.videoRender = null
    }
    if (this.videoRender === null) {
      var codec = "h264";
      if (msgBuf[24] == 5) {
          codec = "hevc";
      }
      this.videoRender = getJmuxer(this.videoId, codec)
    } else {
      if (msgBuf[24] === 4) { //h264
        this.videoRender.feed({video: msgBuf.slice(28)});
      } else if (msgBuf[24] == 5) {//h265
          this.videoRender.feed({ hevc: msgBuf.slice(28) });
      }
    }
  }
}

export default bsVideo
